$(document).ready(function() {    
    var getCategories = function() {
        var departmentId = $('select[name="department"] option:selected').val();
        if (!departmentId) departmentId = 0;
        var categoryIdUrl = window.location.href.match('/category/([0-9]+)');
        var categoryId = null;
        if (categoryIdUrl) {
            categoryId = categoryIdUrl[1];
        }
        var data = {
            department_id: departmentId,
            category_id: categoryId 
        }        
        $.post('/admin/ajax/get-categories', data, function(response) {            
            var response = JSON.parse(response);
            var startCategory = '<option value="0">Без родительской категории</option>';
            var parentId = $('#parent_category').text();
            if (!parentId) {
                parentId = 0;
            }
            if (departmentId != 0) {
                startCategory = '';
            }
            var select = $('select[name="category"]');
            if (select.attr('content') == "true") {
                startCategory = '';
            }
            select.html(startCategory);            
            for (var i in response) {                
                var category = response[i];                
                var selected = '';
                if (parentId == category.id) {
                    selected = 'selected="selected"';
                }
                var html  = '<option value="' + category.id + '" '+selected+'>';
                    html += category.category_name + ' (' + category.parent_name + ')';
                    html += '</option>';
                $('select[name="category"]').append(html);                
            }                      
        })
    }        
    getCategories();    
    $('select[name="department"]').live('change', function() {
        getCategories();
    })
});